package cn.linkstudy;

import cn.linkstudy.util.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/user/**").permitAll()
                .antMatchers("/db/**").permitAll()
                .antMatchers("/api/chat/**").permitAll() // 新增：允许未登录访问所有chat相关接口
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    System.out.println(
                            "=== Security Debug: Authentication failed for " + request.getRequestURI() + " ===");
                    System.out.println("Request method: " + request.getMethod());
                    System.out.println("Request headers: " + request.getHeaderNames());
                    response.setStatus(401);
                    response.getWriter().write("{\"code\":401,\"message\":\"Authentication required\"}");
                })
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    System.out.println("=== Security Debug: Access denied for " + request.getRequestURI() + " ===");
                    System.out.println("Request method: " + request.getMethod());
                    System.out.println("Access denied exception: " + accessDeniedException.getMessage());
                    response.setStatus(403);
                    response.getWriter().write("{\"code\":403,\"message\":\"Access denied\"}");
                });
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}